package controller

import (
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/bear/wolf/model"
	"github.com/bear/wolf/utils"
	"github.com/gin-gonic/gin"
)

func Adduser(c *gin.Context){
	var req model.RegisterRequest
	
	if err := c.ShouldBindJSON(&req);err !=nil{
		utils.Failed(c,"无效的请求:" + err.Error())
		return
	}
	existuser, _ := model.GetUserByUsername(req.Username)
	if existuser !=nil{
		utils.Failed(c,"数据已存在")
		return
	}
	userInfo := &model.UserInfo{
		Username: req.Username,
		RealName: req.RealName,
		Password: req.Password,
		CreateAt: time.Now(),
		UpdateAt: time.Now(),
	}

	if err := model.CreateUser(userInfo); err !=nil{
		utils.Failed(c,"创建用户失败" + err.Error())
		return
	}
	utils.Success(c,gin.H{
		"id":       userInfo.Id,
		"username": userInfo.Username,
		"realname":  userInfo.RealName,
	})
}

func Login(c *gin.Context){
	var req model.UserInfo
	if err := c.ShouldBindJSON(&req);err !=nil{
		utils.Failed(c,"无效的请求:" + err.Error())
		return
	}
	user,err := model.GetUserByUsername(req.Username)
	if err !=nil{
		utils.Failed(c,"用户不存在")
		return
	}

	if model.CheckPassword(req.Password,user.Password){
		utils.Failed(c,"密码错误")
		return
	}
	tokenStr := model.GetToken(user.Id);

	  // 假设这里是创建资源的逻辑...
	createdData := map[string]string{
		"id":   strconv.Itoa(user.Id),
		"name": user.Username,
		"token" : tokenStr,
	}
	utils.Success(c,createdData)
}

func Mytask(c *gin.Context){
	log.Printf("获取我的任务！！")
	userId := c.GetHeader("user_id")
	if strings.TrimSpace(userId) == ""{
		utils.Failed(c,"userId不能为空:")
		return
	}
	resplist := model.GetMyTaskList(utils.StringToInt(userId))
	utils.Success(c,resplist)
}

func MyProject(c *gin.Context){
	log.Printf("我的项目")
		userId := c.GetHeader("user_id")
	if strings.TrimSpace(userId) == ""{
		utils.Failed(c,"userId不能为空:")
		return
	}
	resplist,_  := model.GetMyPorjectList(utils.StringToInt(userId))
	utils.Success(c,resplist)
}